package gen

import (
	"strings"
)

type CodeBlock struct {
	Head    string
	lines   []string
	builder []string
}

type ICodeBlock interface {
	Build()
	isEnd() bool
	checkStep(trimLine string)
	//添加行表达式
	addLineExpression(lineExpression string)
	addLine(line string)
	getLines() []string
	GetBuilder() []string
	addBuilder(builder string)
	GetDesc() string
}

func build0(block ICodeBlock) {
	var currBlock ICodeBlock
	for _, line := range block.getLines() {
		CurrLine = line
		trimLine := strings.TrimSpace(line)
		if currBlock != nil {
			currBlock.checkStep(trimLine)

			if !currBlock.isEnd() {
				currBlock.addLine(line)
			} else {
				currBlock.Build()
				for _, b := range currBlock.GetBuilder() {
					block.addBuilder(b)
				}
				currBlock = nil
			}
		} else {
			if strings.HasPrefix(trimLine, "#set") {
				//set expression like #set some = {{expression}}
				parts := strings.Split(trimLine, " ")
				Params[parts[1]] = ParseFromExpression(parts[3])

			} else if strings.HasPrefix(trimLine, "#for") {
				//forblock like #for meta in {{classMeta.indexMetas}}
				currBlock = OfForBlock(trimLine)

			} else if strings.HasPrefix(trimLine, "#if") {
				//ifblock like if({{index_name}}.containsKey(key)) {
				currBlock = OfIfBlock(trimLine)

			} else {
				block.addLineExpression(line)
			}
		}
	}
}

func (block *CodeBlock) getLines() []string {
	return block.lines
}

func (block *CodeBlock) addLine(line string) {
	block.lines = append(block.lines, line)
}

func (block *CodeBlock) GetBuilder() []string {
	return block.builder
}

func (block *CodeBlock) addBuilder(builder string) {
	block.builder = append(block.builder, builder)
}
